package com.hightrast.service.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hightrast.service.api.domain.bo.QueryShopifyOrders;
import com.hightrast.service.api.domain.bo.QueryShopifyProduct;
import com.hightrast.service.api.domain.bo.ShopifyOrdersResultEntity;
import com.hightrast.service.api.domain.bo.ShopifyProductResultEntity;
import com.hightrast.service.api.domain.vo.rastUser.QueryUserVendorReportVo;
import com.hightrast.service.api.entity.RastOrders;
import com.hightrast.service.api.entity.RastProducts;
import com.hightrast.service.component.ShopifyApiComponent;
import com.hightrast.service.converToClassMapper.ProductMapper;
import com.hightrast.service.service.IRastOrdersService;
import com.hightrast.service.service.IRastProductsService;
import com.hightrast.service.service.IRastUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@EnableScheduling
@Component
@Slf4j
public class ScheduledTask {

    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private IRastUserService userService;
    @Resource
    private IRastOrdersService ordersService;
    @Resource
    private IRastProductsService productsService;
    @Resource
    private ShopifyApiComponent shopifyApiComponent;

    /**
     * 每月1号最近的工作日执行推送数据任务 通过zone = "Asia/Shanghai"设置时区
     */
    @Scheduled(cron = "0 0 9 1 * ? ")
    public void salesDataPushTask() {
        log.info("执行每月推送销售数据任务");
        String contentMessage = "<p>Hi {},</p>\n" +
                "<p>Please find below the sales report for your products on our platform:</p>\n" +
                "<p><b>{} Sales Report:</b></p>\n" +
                "<p>Quantity Sold: {}</p>\n" +
                "<p>Total Revenue: {}</p>\n" +
                "<p>Commission Percentage: {}</p>\n" +
                "<p>Transferable Amount: {}</p>\n" +
                "<p>Transfer before: 10th of next month</p>\n" +
                "<p>Thank you for your partnership.</p>\n" +
                "<p>Best Regards,</p>\n" +
                "<p>Hightrast</p>";
        // 获取设计师关联品牌的销售数据
        List<QueryUserVendorReportVo> reports = userService.queryUserVendorReport();
        MimeMessage message = mailSender.createMimeMessage();
        for (QueryUserVendorReportVo report: reports) {
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message);
                helper.setFrom(from);
                helper.setTo(report.getAccount());
                helper.setSubject("Sales Data");
                String content = StrUtil.format(contentMessage, report.getUserName(), report.getVendor(),report.getQuantity(), report.getTotalCommissonPay(), report.getCommissonRate(), report.getTransferableAmount());
                // 不加参数默认是文本，加上true之后支持html格式文件
                helper.setText(content, true);
                mailSender.send(helper.getMimeMessage());
            } catch (Exception e) {
                log.error("发送邮件报表失败：{}",e.getMessage());
            }
            log.info("数据推送完成");
        }
    }

//    @Scheduled(cron = "0 0 */1 * * ?")
    public void syncProductTask(){
        ShopifyProductResultEntity productResultEntity = shopifyApiComponent.syncProducts();
        if(null == productResultEntity || CollUtil.isEmpty(productResultEntity.getProducts())){
            log.info("获取商品列表为空");
            return;
        }
        List<QueryShopifyProduct> products = productResultEntity.getProducts();
        List<RastProducts> rastProducts = products.stream()
                .map(ProductMapper.INSTANCE::queryShopifyToProduct)
                .collect(Collectors.toList());
        productsService.addProduct(rastProducts);
    }

//    @Scheduled(cron = "0 0 */1 * * ?")
    public void syncOrderTask(){
        ShopifyOrdersResultEntity ordersResultEntity = shopifyApiComponent.syncOrders();
        if(null == ordersResultEntity || CollUtil.isEmpty(ordersResultEntity.getOrders())){
            log.info("获取订单列表为空");
            return;
        }
        List<QueryShopifyOrders> orders = ordersResultEntity.getOrders();
        List<RastOrders> rastOrders = ordersService.addQo(orders);
        ordersService.addOrders(rastOrders);
    }

}
